//用nodejs写一个读取rules目录下dns.rules为名称的文件，按行读取文件内容。遇到空行跳过该行。遇到行首内容是“#”号的也跳过该行。读取剩余每行内容中msg字段的内容，内容是用在msg字段名冒号后，被双引号包围。读取到的msg内容按行写在一个new.text文件中
const fs = require("fs");
const path = require("path");
//deleted , icmp,scada_special 三个文件都是注释掉的，不需要读取
const ruleFiles = [
  "dns.rules",
  "dos.rules",
  "icmp.rules",
  "sql.rules",
  "web_client.rules",
  "web_server.rules",
  "scan.rules",
  "scada.rules",
  "scada_special.rules",
  "web_specific_apps.rules",
  "exploit.rules",
  "deleted.rules"
];

const classtypeArr = [];

//写一个循环读取上面的ruleFiles数组的文件内容，循环里面的标识用f表示文件名
for (let f = 0; f < ruleFiles.length; f++) {
  const filePath = path.join(
    __dirname,
    "../../views/rules/rules/" + ruleFiles[f]
  );
  const file = fs.readFileSync(filePath, "utf8");
  const lines = file.split("\n");
  const newText = [];
  let msg = "";
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i].trim();
    if (line === "" || line.startsWith("#")) {
      continue;
    }
    console.log("lines:", i);
    const index = line.indexOf("msg:");
    if (index > -1) {
      const start = index + 5; //包括msg:"的长度"

      //获取从msg字段名冒号后开始到双引号结束的字符串的位置
      const end = line.indexOf('"', start);

      console.log("lines start:", start, end);
      if (end > -1) {
        msg = line.substring(start, end);
        console.log("msg:", msg);
        newText.push(msg);
      }

      const classtypeindex = line.indexOf("classtype:");

      if (classtypeindex > -1) {
        const startClass = classtypeindex + 10; //包括classtype:"的长度"

        const endClass = line.indexOf(";", startClass);
        if (endClass > -1) {
          const classtype = line.substring(startClass, endClass);
          //如果classtype不存在，则添加到classtypeArr数组中
          if (classtypeArr.indexOf(classtype) === -1) {
            classtypeArr.push(classtype);
          }
        }
      }
    }
  }
  // const newFilePath = path.join(
  //   __dirname,
  //   "../../views/rules/get/" + ruleFiles[f] + ".txt"
  // );
  // const newFilePath = path.join(__dirname, "../../views/rules/get/all.txt");
  // fs.writeFileSync(newFilePath, newText.join("\n"));
  // console.log(ruleFiles[f] + ".txt file created successfully!");

  // 使用 appendFileSync 在文件末尾添加内容
  // fs.appendFileSync(filePath, content);
}

console.log("classtypeArr:", classtypeArr);
